﻿using System;
using System.ComponentModel;
using System.Text;

namespace WebSite.Class
{
    public static class Extension
    {
        public static string ToConcatString(this string[] strs, char concatChar)
        {
            var build = new StringBuilder();
            foreach (var item in strs)
            {
                build.AppendFormat("{0}{1}", item, concatChar);
            }

            return build.ToString().TrimEnd(concatChar);
        }

        /// <summary>
        /// 获取枚举的Description特性的描述
        /// </summary>
        /// <param name="enumObj"></param>
        /// <param name="isEnumSelf">是否显示的enum类型上的Description还是当前枚举值的</param>
        /// <returns></returns>
        public static string GetDescription(this object enumObj, bool isEnumSelf = false)
        {
            var description = string.Empty;
            try
            {
                if (enumObj != null)
                {
                    var enumType = enumObj.GetType();
                    DescriptionAttribute desAttr;
                    if (isEnumSelf)
                    {
                        desAttr = (DescriptionAttribute)Attribute.GetCustomAttribute(enumType,
                            typeof(DescriptionAttribute));
                    }
                    else
                    {
                        var field = enumType.GetField(Enum.GetName(enumType, enumObj));
                        desAttr = (DescriptionAttribute)Attribute.GetCustomAttribute(field,
                            typeof(DescriptionAttribute));
                    }

                    if (desAttr != null)
                    {
                        description = desAttr.Description;
                    }
                }
            }
            catch
            {
                return string.Empty;
            }

            return description;
        }
    }
}